package com.zxl.study.support;


import com.google.gson.Gson;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.util.ReflectionUtils;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;


/**
 * 类型转换工具类
 */
@Slf4j
public class BeanHelper {

    private BeanHelper() {
    }

    private static Gson gson = new Gson();

    public static <T> T copyProperties(Object source, Class<T> target) {
        try {
            T t = target.newInstance();
            BeanUtils.copyProperties(source, t);
            return t;
        } catch (Exception e) {
            throw new RuntimeException("异常");


        }
    }

    public static <T> List<T> copyWithCollection(List<?> sourceList, Class<T> target) {
        try {
            return sourceList.stream().map(s -> copyProperties(s, target)).collect(Collectors.toList());
        } catch (Exception e) {
            throw new RuntimeException("异常");

        }
    }

    public static <T> Set<T> copyWithCollection(Set<?> sourceList, Class<T> target) {
        try {
            return sourceList.stream().map(s -> copyProperties(s, target)).collect(Collectors.toSet());
        } catch (Exception e) {
            throw new RuntimeException("异常");

        }
    }

    public static <T> T copyWithMap(Map<?, ?> sourceMap, Class<T> target) {
        try {
            String json = gson.toJson(sourceMap);
            return gson.fromJson(json, target);
        } catch (Exception e) {
            throw new RuntimeException("异常");

        }
    }

    public static Map<String, Object> objectToMap(Object obj) {
        Map<String, Object> map = new HashMap<>();
        try {
            Class<?> clazz = obj.getClass();
            for (Field field : clazz.getDeclaredFields()) {
                ReflectionUtils.makeAccessible(field);
                String fieldName = field.getName();
                Object value = field.get(obj);
                map.put(fieldName, value);
            }
        } catch (IllegalAccessException e) {
            throw new RuntimeException("异常");
        }
        return map;
    }
}
